const express = require('express');
const path = require('path');
const tokenService = require('./lib/service/token');
const xmlParser = require('express-xml-bodyparser');
const logger = require('morgan');
const { UI } = require('bull-board');
const fs = require('fs');
const fileStreamRotator = require('file-stream-rotator');
// const sysConfig = require('./config/sys.json');

const app = express();
///
// 开放CORS限定
app.all('*', function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length, Authorization, Accept,X-Requested-With');
    res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
    if (req.method === 'OPTIONS') {
        res.send(200);
    } else {
        next();
    }
});

// ============================== 加载中间件 ===================================
app.use(express.json({ limit: '100mb' })); // json大小限制
app.use(xmlParser({ // XML请求处理解析中间件
    explicitArray: false
}));
app.use(express.urlencoded({ extended: false })); // url解码设定
app.use(express.static(path.join(__dirname, 'framework/public'))); // 静态资源
// app.use(express.static(sysConfig.publicPath)); // 静态资源

// ============================== 授权TOKEN解析 ===================================
app.use(async (req, res, next) => {
    try {
        if (req.headers.authorization && req.headers.authorization !== '') {
            let tokenData;
            try {
                tokenData = await tokenService.parseMiniProgramToken(req.headers.authorization);
            } catch (e) {
                tokenData = await tokenService.parseAdminSiteToken(req.headers.authorization);
            }
            req.auth = {};
            for (let key in tokenData) {
                if (key !== 'exp' && key !== 'iat') {
                    req.auth[key] = tokenData[key];
                }
            }
        }
    } catch (e) {
        req.auth = undefined;
    }
    next();
});

// 日志
logger.token('id', function (req) {
    return req.auth ? (req.auth.userId || req.auth.adminId) : '';
});
logger.format('selfFormat', ' :id :remote-addr - :remote-user [:date[clf]] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"');
const logDirectory = path.join(__dirname, '/logs');
fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory);
const accessLogStream = fileStreamRotator.getStream({
    filename: logDirectory + '/accss-%DATE%.log',
    frequency: 'daily',
    verbose: false,
    size: '50m',
    max_logs: 100
});
app.use(logger('selfFormat', { stream: accessLogStream }));

// ============================== 加载路由 ===================================
function loadRoute (routeFile) {
    const route = require(routeFile.substring(0, routeFile.lastIndexOf('.')));
    app.use(route.basePath, route.router);
}

function listDir (baseDir) {
    const fileList = fs.readdirSync(baseDir, 'utf-8');
    for (let i = 0; i < fileList.length; i++) {
        const stat = fs.lstatSync(baseDir + '/' + fileList[i]);
        // 是目录，需要继续
        if (!stat.isDirectory()) {
            loadRoute(baseDir + '/' + fileList[i]);
        }
    }
}

listDir(path.join(__dirname, './framework/routes'));

// ============================== 其他组件路由 ===================================
app.use('/queues', UI);

module.exports = app;
